package com.lecyon.farm.util;

import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 复制对象的非空属性值
 *
 * @author Yao Zheng
 * @Date 2020/3/2 17:26
 */
public class CopyUtils {

    public static void copyBeanIgnoreNull(Object source, Object target, String... ignore) throws Exception {
        Objects.requireNonNull(source);
        Objects.requireNonNull(target);
        List<String> ignoreCopyProperties = Lists.newArrayList();
        if (ignore != null) {
            ignoreCopyProperties.addAll(Arrays.asList(ignore));
        }
        Field[] fields = source.getClass().getDeclaredFields();
        for (int i = fields.length - 1; i >= 0; i--) {
            Field field = fields[i];
            //打开私有访问
            boolean canAccess = field.canAccess(source);
            if (!canAccess) {
                field.setAccessible(true);
            }
            Object fieldValue = field.get(source);
            if (fieldValue == null) {
                ignoreCopyProperties.add(field.getName());
            }
            field.setAccessible(canAccess);
        }
        BeanUtils.copyProperties(source, target, ignoreCopyProperties.toArray(new String[]{}));
    }

}
